package com.longdaji.decoration.ui.pay;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.longdaji.decoration.R;
import com.longdaji.decoration.base.BaseActivity;
import com.longdaji.decoration.bean.Account;
import com.longdaji.decoration.data.bean.AddressBean;
import com.longdaji.decoration.data.bean.AvailableMoneyBean;
import com.longdaji.decoration.data.bean.AvailableScoreBean;
import com.longdaji.decoration.data.bean.GoodsAccountBean;
import com.longdaji.decoration.data.bean.LogisticsBean;
import com.longdaji.decoration.data.bean.PakageBean;
import com.longdaji.decoration.data.bean.PayRequestBean;
import com.longdaji.decoration.data.bean.PayResult;
import com.longdaji.decoration.ui.activitiesOfMine.receivingAddress.ReceivingAddressActivity;
import com.longdaji.decoration.ui.payOrder.PayOrderActivity;
import com.longdaji.decoration.utils.ImageUtil;
import com.longdaji.decoration.utils.LogUtil;
import com.longdaji.decoration.utils.StringUtil;
import com.longdaji.decoration.widget.LogisticsDialog;
import com.longdaji.decoration.widget.PackageDialog;
import com.longdaji.decoration.widget.PayDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by longtao on 2017/12/19.
 */

public class PayActivity extends BaseActivity implements PayContract.View, CompoundButton.OnCheckedChangeListener {

    private static final String TAG = PayActivity.class.getSimpleName();
    private static final int REQUEST_ADD_ADDR = 0;
    private static final int REQUEST_UPDATE_ADDR = 1;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.llyt_add_addr)
    LinearLayout mLlytAddAddr;
    @BindView(R.id.llyt_addr_all)
    LinearLayout mLlytAddrAll;
    @BindView(R.id.rlyt_addr_default)
    RelativeLayout mRlytAddrDefault;
    @BindView(R.id.tv_default_address)
    TextView mTvDefaultAdd;
    @BindView(R.id.tv_receiver)
    TextView mTvReceiverInfo;
    @BindView(R.id.tv_goods_price)
    TextView mTvGoodsPrice;
    @BindView(R.id.tv_freight_charge)
    TextView mTvFreightCharge;
    @BindView(R.id.tv_actual_pay)
    TextView mTvActualPay;
    @BindView(R.id.tv_need_pay)
    TextView mTvNeedPay;
    @BindView(R.id.tv_goods_num)
    TextView mTvGoodsNum;
    @BindView(R.id.iv_sku_image)
    ImageView mIvSkuImage;
    @BindView(R.id.tv_package)
    TextView mTvPackage;
    @BindView(R.id.tv_logistics)
    TextView mTvLogistics;
    @BindView(R.id.tv_pakage_charge)
    TextView mTvPakageCharge;
    @BindView(R.id.tv_score_money)
    TextView mTvScoreMoney;
    @BindView(R.id.tv_left_money_deduction)
    TextView mTvLeftMoneyDeduction;
    @BindView(R.id.tv_score_deduction)
    TextView mTvScoreDeduction;
    @BindView(R.id.tv_left_money)
    TextView mTvLeftMoney;
    @BindView(R.id.cb_score_deduction)
    CheckBox mCbScoreDeduction;
    @BindView(R.id.cb_money_deduction)
    CheckBox mCbMoneyDeduction;
    @BindView(R.id.et_invite_code)
    EditText mEtInviteCode;
    @BindView(R.id.et_remark)
    EditText mEtRemark;
    @Inject
    PayPresenter mPresenter;
    private List<GoodsAccountBean.CartBalance.Address> mAddressList;
    private PayDialog dialog;
    private static final int SDK_PAY_FLAG = 1;
    private PackageDialog mPackageDialog;
    private LogisticsDialog mLogisticsDialog;
    private ArrayList<PayRequestBean> mGoodList;
    private int num;
    private AddressBean.Address mDefaultAddress;
    private double mGoodmoney;
    private double mFreightCharge;
    private double mPakageCharge;
    private double mTotalMoney;
    private PakageBean mSelectPakage;
    private LogisticsBean mSelectLogistics;
    private List<PakageBean> mPakageList;
    private List<LogisticsBean> mLogisticsList;
    private AvailableMoneyBean mMoneyBean;
    private AvailableScoreBean mScoreBean;
    private String mImage;
    private double mScoreMoney;
    private double mLeftMoney;

    public static Intent getStartIntent(Context context) {
        Intent intent = new Intent(context, PayActivity.class);
        return intent;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "PayOrderActivity onCreate");
        setContentView(R.layout.activity_pay);
        setUnBinder(ButterKnife.bind(this));
        initView();
    }

    private void initView() {
        mPresenter.setView(this);
        mTvTitle.setText("商品订单");
        mCbScoreDeduction.setOnCheckedChangeListener(this);
        mCbMoneyDeduction.setOnCheckedChangeListener(this);
        if (getIntent() != null) {
            num = getIntent().getIntExtra("num", 0);
            mGoodmoney = getIntent().getDoubleExtra("money", 0);
            mImage = getIntent().getStringExtra("image");
            mGoodList = getIntent().getParcelableArrayListExtra("good_list");
            mTvGoodsNum.setText(num + "件商品");
            mTvGoodsPrice.setText("¥" + StringUtil.formatNumber(mGoodmoney));
            upadateMoney();
//            mTvActualPay.setText("¥" + mGoodmoney);
//            mTvNeedPay.setText("¥" + mGoodmoney);
            ImageUtil.loadImage(this,mImage,mIvSkuImage);
//            Glide.with(this)
//                    .load(mImage)
//                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
//                    .placeholder(R.drawable.no_banner)
//                    .error(R.drawable.no_banner)
//                    .into(mIvSkuImage);
            // GlideUtils.loadImage(this, image, mIvSkuImage, null, R.drawable.no_banner, R.drawable.no_banner);
        }
        getData();
    }

    @Override
    protected void onDestroy() {
        mPresenter.detachView();
        super.onDestroy();
    }

    private void getData() {
        // mPresenter.getAccountData(1,cartList);
        mPresenter.getDefaultAddress(Account.getInstance().getUserid());
        mPresenter.getLogisticsPattern();
        mPresenter.getPakagePattern();
        mPresenter.getAvailableMoney(Account.getInstance().getUserid());
        mPresenter.getAvailableScore(Account.getInstance().getUserid());
    }

    @OnClick({R.id.iv_back, R.id.rlyt_addr_default, R.id.llyt_add_addr, R.id.btn_submit_order, R.id.rlyt_package, R.id.rlyt_logistics, R.id.btn_add_addr})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rlyt_addr_default:
//                mRlytAddrDefault.setVisibility(View.GONE);
//                mLlytAddrAll.setVisibility(View.VISIBLE);
//                mLlytAddrAll.removeAllViews();
                // addAddrView();
                mPresenter.getAddressList(Account.getInstance().getUserid());
                //  mLlytAddAddr.setVisibility(View.VISIBLE);
                break;
            case R.id.llyt_add_addr:
                mLlytAddrAll.removeAllViews();
                mRlytAddrDefault.setVisibility(View.VISIBLE);
                mLlytAddrAll.setVisibility(View.GONE);
                mLlytAddAddr.setVisibility(View.GONE);
                break;
            case R.id.btn_submit_order:
                if (mEtInviteCode.getText() == null || TextUtils.isEmpty(mEtInviteCode.getText().toString().trim())) {
                    creatOrder();
                } else {
                    mPresenter.verifyInviteCode(mEtInviteCode.getText().toString().trim());
                }

                break;
            case R.id.rlyt_package:
                showPackageDialog();
                break;
            case R.id.rlyt_logistics:
                showLogisticsDialog();
                break;
            case R.id.btn_add_addr:
                Intent intent = ReceivingAddressActivity.getStartIntent(this);
                startActivityForResult(intent, REQUEST_ADD_ADDR);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_ADD_ADDR || requestCode == REQUEST_UPDATE_ADDR) && resultCode == RESULT_OK) {
            mPresenter.getAddressList(Account.getInstance().getUserid());
        }
    }

    private void creatOrder() {
        LogUtil.d(TAG, "creatOrder");
        if (mGoodList == null || mGoodList.size() <= 0) {
            toast("请选择商品");
            return;
        }
        Account account = Account.getInstance();
        if (account == null) {
            toast("请先登录账号");
            return;
        }
        if (mDefaultAddress == null) {
            toast("请添加收货地址");
            return;
        }
        Gson gson = new Gson();
        HashMap<String, Object> paramsMap = new HashMap<>();
        List<String> cartId = new ArrayList<>();
        if (mSelectPakage != null) {
            if (!StringUtil.doubleIsZero(mSelectPakage.getPackageMoney())) {
                paramsMap.put("packageCarriage", mSelectPakage.getPackageMoney());
            } else {
                paramsMap.put("packageCarriage", "0");
            }
            paramsMap.put("isPackage", mSelectPakage.getType());
        }
        if (mCbScoreDeduction.isChecked() && mScoreBean != null) {
            if (!StringUtil.doubleIsZero(getScoreMoney())) {
                paramsMap.put("isIntegral", getScoreMoney() / mScoreBean.getSubRate());
                paramsMap.put("integralCarriage", getScoreMoney() + "");
            } else {
                paramsMap.put("isIntegral", "0");
                paramsMap.put("integralCarriage", "0");
            }

        }
        if (mCbMoneyDeduction.isChecked() && mMoneyBean != null) {
            if (!StringUtil.doubleIsZero(getLeftMoney())) {
                paramsMap.put("isBalance", getLeftMoney() + "");
            } else {
                paramsMap.put("isBalance", "0");
            }
        }
        if (mSelectLogistics != null) {
            paramsMap.put("expressMethod", mSelectLogistics.getType());
            if (!StringUtil.doubleIsZero(mSelectLogistics.getCarriageMoney())) {
                paramsMap.put("orderCarriage", mSelectLogistics.getCarriageMoney() + "");
            } else {
                paramsMap.put("orderCarriage", "0");
            }
        }
        if (mEtInviteCode.getText() != null) {
            paramsMap.put("inviteCode", mEtInviteCode.getText().toString().trim());
        }
        if (mEtRemark.getText() != null) {
            paramsMap.put("userRemark ", mEtRemark.getText().toString().trim());
        }
        paramsMap.put("productAmountTotal", mGoodmoney + "");
        paramsMap.put("productCount", num + "");
        paramsMap.put("shippingId", mDefaultAddress.getShippingId() + "");
        paramsMap.put("userid", account.getUserid());
        List<HashMap<String, Object>> list = new ArrayList<>();
        for (PayRequestBean payRequestBean : mGoodList) {
            cartId.add(payRequestBean.getCartId());
            HashMap<String, Object> good = new HashMap<>();
            good.put("goodsId", payRequestBean.getGoodsId());
            good.put("goodsName", payRequestBean.getGoodsName());
            good.put("goodsPrice", payRequestBean.getGoodsPrice());
            good.put("productNum", payRequestBean.getProductNum());
            good.put("skuId", payRequestBean.getSkuId());
            list.add(good);
        }
        paramsMap.put("goods", list);
        paramsMap.put("cartId", cartId);
        String strEntity = gson.toJson(paramsMap);
        LogUtil.d(TAG, "pay request json=" + strEntity);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        mPresenter.createOrder(body);
    }

    private void showLogisticsDialog() {
        if (mLogisticsDialog == null) {
            mLogisticsDialog = new LogisticsDialog(this, mLogisticsList, new LogisticsDialog.Callback() {
                @Override
                public void onSubmit(LogisticsBean logisticsBean) {
                    mSelectLogistics = logisticsBean;
                    upadateMoney();
                    if (logisticsBean == null) {
                        return;
                    }
                    if (logisticsBean.getName() != null) {
                        mTvLogistics.setText(logisticsBean.getName());
                    }

                }
            });
        }
//            mLogisticsDialog.setData(new LogisticsDialog.Callback() {
//                @Override
//                public void onSubmit(String logistics) {
//                    mTvLogistics.setText(logistics);
//                    double actualMoney = 0;
//                    if (TextUtils.equals("加急", logistics)) {
//                        if (TextUtils.equals("精包装", mTvPackage.getText())) {
//                            actualMoney = mGoodmoney + MONEY_EMERGENCY_LOGISTICS + MONEY_DELICAVY_PAKAGE;
//                        } else {
//                            actualMoney = mGoodmoney + MONEY_EMERGENCY_LOGISTICS;
//                        }
//                        mTvFreightCharge.setText("¥" + MONEY_EMERGENCY_LOGISTICS);
//                    } else {
//                        if (TextUtils.equals("精包装", mTvPackage.getText())) {
//                            actualMoney = mGoodmoney + MONEY_DELICAVY_PAKAGE;
//                        } else {
//                            actualMoney = mGoodmoney;
//                        }
//                        mTvFreightCharge.setText("¥" + MONEY_NORMAL_LOGISTICS);
//                    }
//                    mTvNeedPay.setText("¥" + actualMoney);
//                    mTvActualPay.setText("¥" + actualMoney);
//                }
//            });
        //    }
        mLogisticsDialog.show();
    }

    private void showPackageDialog() {
        if (mPackageDialog == null) {
            mPackageDialog = new PackageDialog(this, mPakageList, new PackageDialog.Callback() {
                @Override
                public void onSubmit(PakageBean pakageBean) {
                    mSelectPakage = pakageBean;
                    upadateMoney();
                    if (pakageBean == null) {
                        return;
                    }
                    if (pakageBean.getName() != null) {
                        mTvPackage.setText(pakageBean.getName());
                    }
                }
            });
//            mPackageDialog.setData(mPakageList,new PackageDialog.Callback() {
//                @Override
//                public void onSubmit(PakageBean pakageBean) {
//                    if(pakageBean==null){
//                        return;
//                    }
//                    mTvPackage.setText(pakageBean.getName());
//                    double actualMoney = 0;
//                    if (TextUtils.equals("精包装", pakageBean.getName())) {
//                        if (TextUtils.equals("加急", mTvLogistics.getText())) {
//                            actualMoney = money + MONEY_DELICAVY_PAKAGE + MONEY_EMERGENCY_LOGISTICS;
//                        } else {
//                            actualMoney = money + MONEY_DELICAVY_PAKAGE;
//                        }
//                    } else {
//                        if (TextUtils.equals("加急", mTvLogistics.getText())) {
//                            actualMoney = money + MONEY_EMERGENCY_LOGISTICS;
//                        } else {
//                            actualMoney = money;
//                        }
//                    }
//                    mTvNeedPay.setText("¥" + actualMoney);
//                    mTvActualPay.setText("¥" + actualMoney);
//                }
//            });
        }
        mPackageDialog.show();
    }

    private double getTotalMoney() {
        double total = mGoodmoney;
        if (mSelectLogistics != null) {
            total += mSelectLogistics.getCarriageMoney();
        }
        if (mSelectPakage != null) {
            total += mSelectPakage.getPackageMoney();
        }
        if (mCbScoreDeduction.isChecked()) {
            if (mScoreBean != null) {
                if (total - mScoreBean.getCanUseScoreBalance() >= 0.1) {
                    total -= mScoreBean.getCanUseScoreBalance();
                } else {
                    total = 0.1;
                }

            }
        }
        if (mCbMoneyDeduction.isChecked()) {
            if (mMoneyBean != null) {
                if (total - mMoneyBean.getTotalBalance() >= 0.1) {
                    total -= mMoneyBean.getTotalBalance();
                } else {
                    total = 0.1;
                }

            }
        }

        return total;
    }

    private void addAddrView(final List<AddressBean.Address> addressList) {
        for (int i = 0; i < addressList.size(); i++) {

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            LayoutInflater inflater = LayoutInflater.from(this);
            String phone = addressList.get(i).getContactTelephone();
            final String info;
            if (phone != null) {
                //info=mAddressList.get(i).getContactPerson()+" "+phone.substring(0,3)+"****"+phone.substring(7);
                info = addressList.get(i).getContactPerson() + " " + phone;
            } else {
                info = addressList.get(i).getContactPerson();
            }

            View view = inflater.inflate(R.layout.item_addr_info, null);
            TextView addr = view.findViewById(R.id.tv_addr);
            TextView receiverInfo = view.findViewById(R.id.tv_receiver);
            receiverInfo.setText(info);
            addr.setText(addressList.get(i).getSimpleAddress() + addressList.get(i).getDetailAddress());
            TextView defaultBg = view.findViewById(R.id.tv_default_bg);
            RelativeLayout addrLayout = view.findViewById(R.id.rlyt_addr_single);
            ImageView edit = view.findViewById(R.id.iv_edit);
            final int finalI = i;
            edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = ReceivingAddressActivity.getStartIntent(PayActivity.this);
                    intent.putExtra("addr_bean", addressList.get(finalI));
                    startActivityForResult(intent, REQUEST_UPDATE_ADDR);
                }
            });
            addrLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mDefaultAddress = addressList.get(finalI);
                    mLlytAddrAll.removeAllViews();
                    mRlytAddrDefault.setVisibility(View.VISIBLE);
                    mTvReceiverInfo.setText(info);
                    mTvDefaultAdd.setText(addressList.get(finalI).getSimpleAddress() + addressList.get(finalI).getDetailAddress());
                    mLlytAddrAll.setVisibility(View.GONE);
                    mLlytAddAddr.setVisibility(View.GONE);
                }
            });
            if (TextUtils.equals("1", addressList.get(i).getDefaultAddress())) {
                defaultBg.setVisibility(View.VISIBLE);
            }
            view.setLayoutParams(lp);
            mLlytAddrAll.addView(view);
        }

    }

    @Override
    public void showData(GoodsAccountBean goodsAccountBean) {
        mAddressList = goodsAccountBean.getCartBalance().getAddressList();
        mTvDefaultAdd.setText(mAddressList.get(0).getDetailAddress());
        String receiverPhone = mAddressList.get(0).getContactTelephone();
        //String receiverInfo=mAddressList.get(0).getContactPerson()+receiverPhone.substring(0,3)+"****"+receiverPhone.substring(7);
        String receiverInfo = mAddressList.get(0).getContactPerson() + " " + receiverPhone;
        mTvReceiverInfo.setText(receiverInfo);
        int num = 0;
        for (GoodsAccountBean.CartBalance.CartGoods cartGoods : goodsAccountBean.getCartBalance().getCartBalanceGoodsList()) {
            num += cartGoods.getGoodsSkuNum();
        }
        mTvGoodsNum.setText(num + "件商品");
        mTvGoodsPrice.setText("¥" + StringUtil.formatNumber(goodsAccountBean.getCartBalance().getTotal()));
        double actualPay = goodsAccountBean.getCartBalance().getTotal();
        mTvActualPay.setText("¥" + StringUtil.formatNumber(actualPay));
        mTvNeedPay.setText("¥" + StringUtil.formatNumber(actualPay));

    }

    @Override
    public void showDefaultAddress(AddressBean.Address address) {
        mDefaultAddress = address;
        mTvDefaultAdd.setText(address.getSimpleAddress() + address.getDetailAddress());
        String receiverPhone = address.getContactTelephone();
        //String receiverInfo=mAddressList.get(0).getContactPerson()+receiverPhone.substring(0,3)+"****"+receiverPhone.substring(7);
        String receiverInfo = address.getContactPerson() + " " + receiverPhone;
        mTvReceiverInfo.setText(receiverInfo);
    }

    @Override
    public void showNoDefaultAddress() {
        mRlytAddrDefault.setVisibility(View.GONE);
        mLlytAddrAll.setVisibility(View.GONE);
        mLlytAddAddr.setVisibility(View.VISIBLE);
    }

    @Override
    public void showCreateOrderFail() {
        toast("生成订单失败！");
    }

    @Override
    public void showCreateOrderSuccess(final String orderId) {
//        if (dialog == null) {
//            dialog = new PayDialog(this);
//            dialog.setData(new PayDialog.Callback() {
//                @Override
//                public void onSubmit() {
//                    Log.d(TAG, "PayDialog onSubmit");
//                    mPresenter.getPayOrderInfo(orderId);
//                }
//
//                @Override
//                public void onCancle() {
//                    Log.d(TAG, "PayDialog onCancle");
//                }
//            });
//        }
//        dialog.show();
        Intent intent = PayOrderActivity.getStartIntent(this);
        intent.putExtra("num", num);
        intent.putExtra("good_money", mGoodmoney);
        intent.putExtra("pakage_money", mSelectPakage.getPackageMoney());
        intent.putExtra("logistics_money", mSelectLogistics.getCarriageMoney());
        intent.putExtra("left_money", getLeftMoney());
        intent.putExtra("score_money", getScoreMoney());
        intent.putExtra("total_money", getTotalMoney());
        intent.putExtra("image", mImage);
        intent.putExtra("addr", mDefaultAddress);
        intent.putExtra("orderId", orderId);
        startActivity(intent);
    }

    @Override
    public void showDefaultPakage(List<PakageBean> pakageList) {
        mPakageList = pakageList;
        mSelectPakage = pakageList.get(0);
        if (mSelectPakage.getName() != null) {
            mTvPackage.setText(mSelectPakage.getName());
        }
        upadateMoney();
    }

    private double getLeftMoney() {
        double money = 0;
        double total = mGoodmoney;
        if (mSelectLogistics != null) {
            total += mSelectLogistics.getCarriageMoney();
        }
        if (mSelectPakage != null) {
            total += mSelectPakage.getPackageMoney();
        }

        if (mCbScoreDeduction.isChecked()) {
            if (mScoreBean != null) {
                if (total - mScoreBean.getCanUseScoreBalance() >= 0.1) {
                    total -= mScoreBean.getCanUseScoreBalance();
                } else {
                    total = 0.1;
                }

            }
        }
        if (mCbMoneyDeduction.isChecked()) {
            if (mMoneyBean != null) {
                if (total - mMoneyBean.getTotalBalance() >= 0.1) {
                    total -= mMoneyBean.getTotalBalance();
                    money = mMoneyBean.getTotalBalance();
                } else {
                    money = total - 0.1;
                }

            }
        } else {
            money = 0;
        }
        return money;
    }

    private double getScoreMoney() {
        double money = 0;
        double total = mGoodmoney;
        if (mSelectLogistics != null) {
            total += mSelectLogistics.getCarriageMoney();
        }
        if (mSelectPakage != null) {
            total += mSelectPakage.getPackageMoney();
        }

        if (mCbScoreDeduction.isChecked()) {
            if (mScoreBean != null) {
                if (total - mScoreBean.getCanUseScoreBalance() >= 0.1) {
                    money = mScoreBean.getCanUseScoreBalance();
                } else {
                    money = total - 0.1;
                }

            }
        } else {
            money = 0;
        }

        return money;
    }

    private void upadateMoney() {
        double total = mGoodmoney;

        if (mSelectPakage != null) {
            total += mSelectPakage.getPackageMoney();
            mTvPakageCharge.setText("¥" + StringUtil.formatNumber(mSelectPakage.getPackageMoney()));
        }
        if (mSelectLogistics != null) {
            total += mSelectLogistics.getCarriageMoney();
            mTvFreightCharge.setText("¥" + StringUtil.formatNumber(mSelectLogistics.getCarriageMoney()));
        }
        if (mCbScoreDeduction.isChecked() && mScoreBean != null) {

            if (total - mScoreBean.getCanUseScoreBalance() >= 0.1) {
                total -= mScoreBean.getCanUseScoreBalance();
                mTvScoreDeduction.setText("-¥" + StringUtil.formatNumber(mScoreBean.getCanUseScoreBalance()));
            } else {
                mTvScoreDeduction.setText("-¥" + StringUtil.formatNumber(total - 0.1));
                total = 0.1;
            }

        } else {
            mTvScoreDeduction.setText("-¥0.00");
        }

        if (mCbMoneyDeduction.isChecked() && mMoneyBean != null) {
            if (total - mMoneyBean.getTotalBalance() >= 0.1) {
                total -= mMoneyBean.getTotalBalance();
                mTvLeftMoneyDeduction.setText("-¥" + StringUtil.formatNumber(mMoneyBean.getTotalBalance()));
            } else {
                mTvLeftMoneyDeduction.setText("-¥" + StringUtil.formatNumber(total - 0.1));
                total = 0.1;
            }
        } else {
            mTvLeftMoneyDeduction.setText("-¥0.00");
        }

        mTvActualPay.setText("¥" + StringUtil.formatNumber(

                getTotalMoney()));
        mTvNeedPay.setText("¥" + StringUtil.formatNumber(

                getTotalMoney()));
    }

    @Override
    public void showNoPakage() {
        toast("获取包装方式失败");
    }

    @Override
    public void showDefaultLogistics(List<LogisticsBean> logisticsList) {
        mLogisticsList = logisticsList;
        mSelectLogistics = logisticsList.get(0);
        if (mSelectLogistics.getName() != null) {
            mTvLogistics.setText(mSelectLogistics.getName());
        }
        upadateMoney();
    }

    @Override
    public void showNoLogistics() {
        toast("获取物流方式失败");
    }

    @Override
    public void showAvailableScore(AvailableScoreBean scoreBean) {
        mScoreBean = scoreBean;
        mTvScoreMoney.setText(StringUtil.formatNumber(scoreBean.getCanUseScoreBalance()));
    }

    @Override
    public void showDefaultAvailableScore() {
        toast("获取积分失败");
    }

    @Override
    public void showAvailableMoney(AvailableMoneyBean moneyBean) {
        mMoneyBean = moneyBean;
        mTvLeftMoney.setText(StringUtil.formatNumber(moneyBean.getTotalBalance()));

    }

    @Override
    public void showDefaultAvailableMoney() {
        toast("获取余额失败");
    }

    @Override
    public void showInviteCodeValid() {
        creatOrder();
    }

    @Override
    public void showInviteCodeInvalid() {
        toast("邀请码填写错误");
    }

    @Override
    public void showAddressList(List<AddressBean.Address> addressList) {
        mRlytAddrDefault.setVisibility(View.GONE);
        mLlytAddrAll.setVisibility(View.VISIBLE);
        mLlytAddrAll.removeAllViews();
        addAddrView(addressList);
        mLlytAddAddr.setVisibility(View.VISIBLE);
    }

    @Override
    public void showGetOrderInfoSuccess(String orderInfo) {
        //String orderInfo1 = "alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2016091200490610&biz_content=%7B%22body%22%3A%221%22%2C%22out_trade_no%22%3A%2210000098778%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%221%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F120.55.48.242%3A8112%2Fpay%2F600003&sign=hk5UrJ5aTioKvV5bhB6SdsSY3%2FKUyUwMBnNgjzH50CdvSInj37GGuNLRY3gcJVsqDjambGxu7sHSR5mbKkO70nm6cXfnxTr5zNFfRh4C%2FQ4wgXon58J2rPVEmgw8NG1SZMLBWyVg0iTUr6j8FeFrT5PiIgU2yR3itWE80kKE%2Bdbv0qa3YBGaduJiqbv2XJtN2iMT04dBJD%2F%2F6TD4vpWJT9U9gPumUuEDHaCvWDQJlKeBBY1Z61h82F4zQjfnG8F5QLSWxtw4UUpm%2FnfS4REyQMuN9%2FgfR4Xhm1ukArVp4SSpfVSzL2ArZC%2FJNNfzFWTWdsRzLYhz4lYHK%2FBp2m3dkw%3D%3D&sign_type=RSA2&timestamp=2018-04-03+23%3A52%3A24&version=1.0";
        aliPay(orderInfo);
    }

    @Override
    public void showGetOrderInfoFail() {
        //String orderInfo1 = "alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2018031802400827&biz_content=%7B%22body%22%3A%221%22%2C%22out_trade_no%22%3A%2210000098778%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%221%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F120.55.48.242%3A8112%2Fpay%2F600003&sign=rPRGLiT8lP31iUGSnKQm7v8mYmDsCwT7tLdoqNE97PKCUhimnSDpoLA%2FbD3JoaMNdEqpJCmmSuc4GFNmorzsQmANVcNHJ5FVKE22Dlsrsqs0yNj84brfeWwqSFQt4MVAZItpUxChPyHiETx7rMEqyVm2eZhNGCgmB3Z3kSO5lWUjfInE6Zm7pYwg1tITgK%2Fqv2Hm4feDXV91kYoNHxvkjALnsypH5Q5rChAXyxaiVQzuAd%2Bj1%2F7B8GmjyO7dQRyNbLBlYZX48X0dBJ5uG2U9YJVXztdsv%2FRxoeila5j3LyuekXEVFGrozI4q71xdZTnl%2FCtlAj8hGDk0XCtiluqcyw%3D%3D&sign_type=RSA2&timestamp=2018-04-04+00%3A29%3A00&version=1.0";
        //aliPay(orderInfo1);
        toast("支付失败！");
    }

    /**
     * 支付宝支付业务
     */
    public void aliPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.d("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        switch (compoundButton.getId()) {
            case R.id.cb_score_deduction:
//                if (b) {
//                    mScoreMoney = mScoreBean.getCanUseScoreBalance();
//                } else {
//                    mScoreMoney = 0;
//                }

                upadateMoney();
                break;
            case R.id.cb_money_deduction:
//                if (b) {
//                    mLeftMoney = mMoneyBean.getTotalBalance();
//                } else {
//                    mLeftMoney = 0;
//                }
                upadateMoney();
                break;

        }
    }
}
